package br.com.android.aluno.view;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class BuscarActivity extends Activity implements OnClickListener {

	// Widgets
	private EditText etBuscar = null;
	private RadioButton rbId = null;
	private RadioButton rbNome = null;
	private Button btBuscar = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buscar);
		
		getBtBuscar().setOnClickListener(this);
		getRbId().setOnClickListener(this);
		getRbNome().setOnClickListener(this);
	}
	
	public void onClick(View v) {
		if(v == getBtBuscar()){
			String valorParaBuscar = getEtBuscar().getText().toString().trim();			
			Log.d("aluno", "Valor a buscar: " + valorParaBuscar);
			

			// Envia o valor a ser buscado para EditarActivity
			Intent it = new Intent(this, EditarActivity.class);
			
			if(getRbId().isChecked()){
				try {
					// Checa se o ID digitado é um número válido
					Long.parseLong(valorParaBuscar);					
					
					it.putExtra(EditarActivity.INTENT_EXTRA_DATA_ID, valorParaBuscar);
					
				} catch (NumberFormatException e) {
					Toast.makeText(getApplicationContext(), "Digite um número inteiro válido para o ID!", Toast.LENGTH_SHORT).show();
					return;
				}
			} else{
				it.putExtra(EditarActivity.INTENT_EXTRA_DATA_NOME, valorParaBuscar);
			}
			
			startActivity(it);
			
			// Encerra essa Activity
			finish();
			
		} else if(v == getRbId()){
			getEtBuscar().setInputType(InputType.TYPE_CLASS_NUMBER);
			
		} else if(v == getRbNome()){
			getEtBuscar().setInputType(InputType.TYPE_CLASS_TEXT);
			
		}
	}	
	
	
	/****************************************************************************
     * 
     * Obtem as referencias aos widgets criando uma instancia unica
     *  
     */
	
	private RadioButton getRbId() {
		if(rbId == null){
			rbId = (RadioButton) findViewById(R.id.activity_busca_rbId);
		}
		
		return rbId;
	}
	
	private RadioButton getRbNome() {
		if(rbNome == null){
			rbNome = (RadioButton) findViewById(R.id.activity_busca_rbNome);
		}
		
		return rbNome;
	}
	
	private EditText getEtBuscar() {
		if(etBuscar == null){
			etBuscar = (EditText) findViewById(R.id.activity_busca_etBuscar);
		}
		
		return etBuscar;
	}
	
	private Button getBtBuscar() {
		if(btBuscar == null){
			btBuscar = (Button) findViewById(R.id.activity_busca_btBuscar);
		}
		
		return btBuscar;
	}
}
